﻿namespace Okazuki.MVVM.PrismSupport.ViewModels.Utils
{
    using System;
    using Microsoft.Practices.Prism.Commands;
    using Okazuki.MVVM.PrismSupport.Utils;

    public class ViewModelInitializer
    {
        /// <summary>
        /// ViewModelの初期化を行います。
        /// </summary>
        /// <param name="viewModel"></param>
        public static void InitializeViewModel(ViewModelBase viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            var info = ViewModelReflectionUtil.GetViewModelInfo(viewModel.GetType());
            foreach (var item in info.AutoInitCommands)
            {
                DelegateCommandFactory.CreateAndSetCommand(viewModel, item.Value);
            }

            foreach (var command in info.CommandProperties.Values)
            {
                EventHandler eventHandler = MakeEventHandler((DelegateCommandBase)command.GetValue(viewModel, null));
                CommandManager.RequerySuggested += eventHandler;
                viewModel.RequerySuggestedEventHandlers.Add(eventHandler);
            }
        }

        /// <summary>
        /// CommandのCanExecuteを呼び出すデリゲートを作成する
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        internal static EventHandler MakeEventHandler(DelegateCommandBase command)
        {
            return (sender, e) => command.RaiseCanExecuteChanged();
        }

    }
}
